import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/store/auth'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { 
      public: true,
      title: '登录'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { 
      public: true,
      title: '注册' 
    }
  },
  {
    path: '/',
    component: () => import('@/views/Layout.vue'),
    meta: { 
      requiresAuth: true 
    },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { 
          title: '首页',
          permissions: ['dashboard:view'] 
        }
      },
      {
        path: 'purchase-requests',
        name: 'PurchaseRequests',
        component: () => import('@/views/purchase-request/List.vue'),
        meta: { 
          title: '采购申请列表',
          permissions: ['purchase_request:read'] 
        }
      },
      {
        path: 'purchase-requests/create',
        name: 'CreatePurchaseRequest',
        component: () => import('@/views/purchase-request/Create.vue'),
        meta: { 
          title: '创建采购申请',
          permissions: ['purchase_request:create'] 
        }
      },

      {
        path: 'purchase-requests/:id',
        name: 'PurchaseRequestDetail',
        component: () => import('@/views/purchase-request/Detail.vue'),
        meta: { 
          title: '采购申请详情',
          permissions: ['purchase_request:read_detail'],
          props: true 
        }
      },

      {
        path: 'purchase-requests/:id/edit',
        name: 'EditPurchaseRequest',
        component: () => import('@/views/purchase-request/Edit.vue'),
        meta: { 
          title: '编辑采购申请',
          permissions: ['purchase_request:update'],
          props: true 
        }
      },

      {
        path: 'approvals',
        name: 'Approvals',
        component: () => import('@/views/approval/List.vue'),
        meta: { 
          title: '待审批列表',
          permissions: ['approval:review'] 
        }
      },
      {
        path: 'approvals/history',
        name: 'ApprovalHistory',
        component: () => import('@/views/approval/History.vue'),
        meta: { 
          title: '审批历史',
          permissions: ['approval_history:read'] 
        }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/User.vue'),
        meta: { 
          title: '用户管理',
          permissions: ['user:management'] 
        }
      },
      {
        path: 'notifications',
        name: 'Notifications',
        component: () => import('@/views/notification/List.vue'),
        meta: { 
          title: '通知列表',
          permissions: ['notification:read'] 
        }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { 
          title: '个人信息',
          permissions: ['profile:manage'] 
        }
      },
      {
        path: 'permissions',
        name: 'Permission',
        component: () => import('@/views/Permissions.vue'),
        meta: { 
          title: '权限分配',
          permissions: ['role:management'] 
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { 
      title: '页面不存在' 
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  console.log(to);
  
  
  // 1. 检查公开路由
  if (to.meta.public) {
    return next()
  }

  // 2. 检查认证状态
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    return next({
      name: 'Login',
      query: { redirect: to.fullPath }
    })
  }

  // 3. 如果已认证但访问登录/注册页，重定向到首页
  if ((to.name === 'Login' || to.name === 'Register') && authStore.isAuthenticated) {
    return next({ name: 'Dashboard' })
  }

  // 4. 检查权限
  if (to.meta.permissions) {
    // 确保权限已加载
    if (authStore.permissions.length === 0) {
      await authStore.loadPermissions()
    }

    console.log(authStore.permissions,authStore.hasPermission(to.meta.permissions));
    console.log(to.meta.permissions);
    
    if (!authStore.hasPermission(to.meta.permissions)) {
      console.warn(`权限不足，需要权限: ${to.meta.permissions.join(', ')}`)
      return next({ name: 'Dashboard' })
    }
  } 

  // 5. 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 采购系统`
  }

  next()
})

export default router